package com.lingxu.base.system.manage.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.system.manage.entity.SysMenu;
import com.lingxu.base.system.manage.entity.SysRoleMenuUserVo;
import com.lingxu.base.system.manage.mapper.SysMenuMapper;
import com.lingxu.base.system.manage.model.SysMenuTree;
import com.lingxu.base.system.manage.service.ISysMenuService;
import com.lingxu.base.system.manage.util.MenuTreeUtil;
import com.lingxu.base.system.manage.vo.LoginUser;
import com.lingxu.base.system.manage.vo.SysOrgMenuOption;
import com.lingxu.base.system.orgManage.vo.MenuTree;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 菜单信息
 * @Author: LingXu
 * @Date:   2021-01-04
 * @Version: V1.0.1
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

     @Resource
     private SysMenuMapper sysMenuMapper;

     private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 菜单信息-分页列表查询
     * @param page 分页信息
     * @param sysMenu 菜单信息
     * @return 菜单信息列表
     */
    @Override
    public IPage<SysMenu> queryPageList(Page<SysMenu> page, SysMenu sysMenu){
        return sysMenuMapper.queryList(page,sysMenu);
    }

    /**
     * 菜单信息-列表查询
     * @param sysMenu 菜单信息
     * @return 菜单信息列表
     */
    @Override
    public List<SysMenu> queryList(SysMenu sysMenu){
        return sysMenuMapper.queryList(sysMenu);
    }

    /**
     * 权限信息-通过用户名查询所拥有的全部权限
     * @param userName
     * @return
     */
    @Override
    public Set<String> getCodeSetByUserName(String userName) {
        return sysMenuMapper.getCodeSetByUserName(userName);
    }

    @Override
    public List<SysMenuTree> getTreeListByUserId(String userId){
        return sysMenuMapper.getTreeListByUserId(userId);
    }

    @Override
    public List<SysMenuTree> getTreeListInManage(SysOrgMenuOption sysOrgMenuOption){
        return sysMenuMapper.getTreeListInManage(sysOrgMenuOption);
    }



    @Override
    public Map<String, List<SysMenu>> getName_NewMenuMap() {
        List<SysMenu> sysMenus=this.list();
        Map<String,List<SysMenu>> name_NewMenuListMap=new HashMap<>();
        for(SysMenu sysMenu:sysMenus){
            List<SysMenu> sysMenuList=name_NewMenuListMap.get(sysMenu.getName());
            if(sysMenuList==null){
                sysMenuList=new ArrayList<>();
                sysMenuList.add(sysMenu);
                name_NewMenuListMap.put(sysMenu.getName(),sysMenuList);
            }else {
                sysMenuList.add(sysMenu);
            }
        }
        return name_NewMenuListMap;
    }

    /*======================================================sys_menu新================================================================*/


    @Override
    public Result findSysMenuList() {
        try {
            List<MenuTree>  menuTrees = sysMenuMapper.findSysMenuListNew();
            for(MenuTree m : menuTrees){
                if(StringUtils.isBlank(m.getPid())){
                    m.setPid("0");
                }
            }
            List<MenuTree> menuTreeList = buildAreaTreeList(menuTrees);
            return Result.ok(menuTreeList,"查询成功");
        }catch (Exception e){
            logger.error("菜单列表数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    private static List<MenuTree> buildAreaTreeList(List<MenuTree> treeList){
        //获取parentId = 0的根节点
        List<MenuTree> areaTrees = treeList.stream().filter(item -> item.getPid().equals("0")).collect(Collectors.toList());
        //根据parentId进行分组
        Map<String,List<MenuTree>> map = treeList.stream().collect(Collectors.groupingBy(MenuTree::getPid));
        recursionFnTree(areaTrees,map);
        return areaTrees;
    }

    private static void recursionFnTree(List<MenuTree> areaTrees,Map<String,List<MenuTree>> map){
        for(MenuTree areaTree : areaTrees){
            List<MenuTree> childList = map.get(areaTree.getId());
            areaTree.setMenuChildTree(childList);
            if (null != childList && 0 < childList.size()){
                recursionFnTree(childList,map);
            }else {
                areaTree.setMenuChildTree(new ArrayList<>());
            }
        }
    }


    @Override
    public Integer findChild(String id) {
        try {
            return sysMenuMapper.findChild(id);
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return 0;
        }
    }


    @Override
    public void deleteSysMenu(List<String> list) {
        try {
            sysMenuMapper.deleteSysMenu(list);
            //删除单位菜单
//            sysMenuMapper.deleteOrgMenu(list);
            //删除对应用户的菜单
            sysMenuMapper.deleteUserMenu(list);
        }catch (Exception e){
            logger.error("操作异常",e);
        }
    }


    @Override
    public Result addMenuButton(SysMenu menuButton) {
        try {
            menuButton.setTypes("2");
            sysMenuMapper.insert(menuButton);
            return Result.ok("操作成功");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public Result updateMenuButton(SysMenu menuButton) {
        try {
            int i = sysMenuMapper.updateById(menuButton);
            if(i > 0){
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public Result deleteMenuButton(String id) {
        try {
            int i = sysMenuMapper.deleteById(id);
            if(i > 0){
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public Result findMenuButtonList(String menuId) {
        try {
            return Result.ok(sysMenuMapper.findMenuButtonList(menuId),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    @Override
    public Result updateSysMenu(SysMenu sysMenu) {
        int i = sysMenuMapper.updateById(sysMenu);
        return Result.ok("操作成功");
    }

    @Override
    public Result findMenuListBycategoryAndId(String category, String id) {
        LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysMenu> list = sysMenuMapper.findMenuListBycategoryAndId(category,id,userNow.getId());
        return Result.ok(list);
    }

    @Override
    public Result findMenuList(SysMenu sysMenu) {
        LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysMenu> list = sysMenuMapper.findMenuList(sysMenu,userNow.getId());
        return Result.ok(list);
    }

    @Override
    public Result findMenuListByUseridAmdMenupid(SysRoleMenuUserVo sysRoleMenuUserVo) {
        LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userid= sysRoleMenuUserVo.getUserid();
        if(StringUtils.isBlank(userid)){
            userid=userNow.getId();
        }
        String menupid = sysRoleMenuUserVo.getMenupid();
        List<SysMenu> list = sysMenuMapper.findMenuListByMenuPidAndUserid(menupid,userid);
        return Result.ok(list);
    }

    /*======================================================sys_menu新================================================================*/


    /**
     * @Author ysj闫世杰
     * @Description 查询未分配菜单
     * @Date 2022/3/4 9:37
     * @Param: roleId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findRoleNotExistMenu(String roleId) {
        try {
            return Result.ok(getMenuTreeHandler(roleId,"0"),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询已分配菜单
     * @Date 2022/3/4 9:37
     * @Param: roleId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findRoleExistMenu(String roleId) {
        try {
            return Result.ok(getMenuTreeHandler(roleId,"1"),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description
     * @Date 2022/3/4 10:50
     * @Param: roleId
     * @return java.util.List<com.lingxu.base.system.orgManage.entity.MenuTree>
     **/
    private List<com.lingxu.base.system.orgManage.entity.MenuTree> getMenuTreeHandler(String roleId, String type) throws Exception{
        List<com.lingxu.base.system.orgManage.entity.MenuTree> rootMenu;
        if("0".equals(type)){
            rootMenu = sysMenuMapper.findRoleNotExistMenu(roleId);
        }else {
            rootMenu = sysMenuMapper.findRoleExistMenu(roleId);
        }
        return new MenuTreeUtil(rootMenu).buildTree();
    }

    /**
     * @Author ysj闫世杰
     * @Description 递归子菜单
     * @Date 2022/3/4 11:00
     * @Param: id
     * @Param: rootMenu
     * @return java.util.List<com.lingxu.base.system.orgManage.entity.MenuTree>
     **/
    private List<com.lingxu.base.system.orgManage.entity.MenuTree> getChild(String id, List<com.lingxu.base.system.orgManage.entity.MenuTree> rootMenu) {
        // 子菜单
        List<com.lingxu.base.system.orgManage.entity.MenuTree> childList = new ArrayList<>();
        for (com.lingxu.base.system.orgManage.entity.MenuTree menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (org.apache.commons.lang.StringUtils.isNotBlank(menu.getPid())) {
                if (menu.getPid().equals(id)) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (com.lingxu.base.system.orgManage.entity.MenuTree menu : childList) {
            // 没有url子菜单还有子菜单
            if (org.apache.commons.lang.StringUtils.isBlank(menu.getUrl())) {
                // 递归
                menu.setMenuChildTree(getChild(menu.getId(), rootMenu));
            }
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

}
